<!--  -->
<template>
  <span class="num din-m" ref="num">{{ num | fomatterNum }}</span>
</template>

<script>
import { merge } from 'lodash-es'
/**
 * 数字组件 zhu18@vip.qq.com at 2020.10.05
 * @default
 *  params:{
 *      num: 0,
 *      animateDuration:.5,
 *
 * @example
 *      <num value="45.2"  />
 *      <num :params="{num:45.23}" />
 *      <num value="45.2"  :params="{animateDuration:2}" />  //2秒动画，
 *
 */
export default {
  name: 'num',
  props: ['params', 'value'],
  components: {},
  data() {
    return {
      num: '',
      //split: true, //千位分割
      //animate
      animateDuration: 0.5,
      isEmpty: false
    }
  },
  filters: {
    fomatterNum(num) {
      if (typeof num === 'number') {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      } else {
        return '-'
      }
    }
  },
  watch: {
    value(v) {
      this.handleData()
      this.init()
    }
  },
  created() {
    this.handleData()
  },
  mounted() {},
  methods: {
    handleData() {
      if (
        typeof this.params.num !== 'number' &&
        typeof this.value !== 'number'
      ) {
        this.isEmpty = true
      }
      this.params.num = parseFloat(this.params.num || this.value || 0)
      // merge(this, this.params)
      // 小数位数
      this._decimalLength = 0
      if (this.num.toString().indexOf('.') != -1)
        this._decimalLength = this.num.toString().split('.')[1].length
      if (this._decimalLength > 2) {
        this.params.num = parseFloat(this.params.num).toFixed(2)
      }
      //动画启始值
      this.num = 0
    },
    init() {
      let tl = new TimelineMax({})
      tl.addLabel('start')
      // if (this.params.num) {
      let step = +Math.pow(0.1, this._decimalLength).toFixed(
        this._decimalLength
      )
      let numOpacity = TweenMax.fromTo(
        this.$refs.num,
        0.2,
        { opacity: 0 },
        { opacity: 1 }
      )

      tl.add(numOpacity, 'start+=0')
      if (!this.isEmpty) {
        let numBeat = TweenMax.to(this, this.animateDuration, {
          num: this.params.num,
          roundProps: { num: step }
        })
        tl.add(numBeat, 'start+=0')
      } else {
        this.num = '-'
      }

      // }
      return tl
    }
  }
}
</script>
<style lang="scss" scoped>
.num {
  opacity: 0;
}
</style>
